package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.LaundryAdapter;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.helper.DBManager;
import com.dlc.beijingrfid.net.bean.BackBean;
import com.dlc.beijingrfid.net.bean.GoodRfidBean;
import com.dlc.beijingrfid.net.bean.HotelBean;
import com.dlc.beijingrfid.net.bean.OrderDetailBean;
import com.dlc.beijingrfid.net.bean.RFIDSpecListBean;
import com.dlc.beijingrfid.net.bean.WashBackBean;
import com.dlc.beijingrfid.net.exception.ErrorMsgException;
import com.dlc.beijingrfid.net.protocol.OrderProto;
import com.dlc.beijingrfid.net.protocol.StockProto;
import com.dlc.beijingrfid.net.protocol.base.HttpProtocol;
import com.dlc.commonlibrary.ble.BleWorker;
import com.dlc.commonlibrary.ble.RfidHelper;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.commonlibrary.widget.popup.CommonPopupList;
import java.util.ArrayList;
import java.util.List;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class SendGoodshActivity extends BaseActivity {
    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.order_number)
    TextView mOrderNumber;
    @BindView(R.id.tv_order)
    TextView mTvOrder;
    @BindView(R.id.drop_order)
    FrameLayout mDropOrder;
    @BindView(R.id.item_order)
    CommonItemView mItemOrder;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.check)
    Button mCheck;
    @BindView(R.id.tv_hotel)
    TextView tvHotel;
    @BindView(R.id.drop_hotel)
    FrameLayout dropHotel;
    @BindView(R.id.item_hotel)
    CommonItemView itemHotel;
    @BindView(R.id.btn_read_rfid)
    Button btnReadRfid;
    @BindView(R.id.order_total)
    TextView mOrderTotal;
    @BindView(R.id.btn_save)
    Button mBtnSave;

    private CommonPopupList mOrderPopup;//酒店
    List<WashBackBean.DataBean.ListBean> OrderList = new ArrayList<>();
    private String OrderId = null;
    private int order_type = 0;
    private List<String> ordernoList = new ArrayList<>();

    private Handler mHandler;
    private LaundryAdapter mLaundryAdapter;

    private int page = 1;
    private ArrayList<String> rfids = new ArrayList<>();
    private List<String> SumList = new ArrayList<>();//手持机整个过程读到的rfid

    private String pagesize = "10000";
    private DBManager dbManager = DBManager.getInstance(this);
    private CommonPopupList mHotelPopup;//酒店
    List<HotelBean.DataBean> HotelList = new ArrayList<>();
    private String HotelId = null;
    BleWorker mBleWorker = new BleWorker();
    private DoResultDialog doReadDialog, doResultDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        titleBar.leftImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.titleText.setText("送货出库");
        mHandler = new Handler();
        initRecyclerView();
        doReadRFID();
        doResult();
        mBleWorker.setCallback(new BleWorker.ReadCallback() {
            @Override
            public void onReceiveData(ArrayList<String> rfidsdata, int readNum) {
                rfids = rfidsdata;
                doReadDialog.dismiss();
                doResultDialog.showResultAndDismiss(true, 1000);
                if (rfids.size() > 0) {
                    doResultDialog.dismiss();
                    queryOrderDetail1(rfids);
                } else {
                    doResultDialog.setFailedText("讀取不到RFID");
                    doResultDialog.setFailedImage(R.mipmap.ic_error);
                    doResultDialog.showResultAndDismiss(false, 2000);
                }
            }

            @Override
            public void onDeviceDisconnected() {
                doReadDialog.dismiss();
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("type", "2");
                startActivity(intent);
            }

            @Override
            public void onErrorNumber(int number) {
                if (number > 0) {
                    showOneToast("存在长度小于14的标签" + number + "个");
                }
            }
        });
        getDbData();
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_send_goods;
    }

    /**
     * 获取数据库的数据
     */
    /**
     * 获取数据库的数据
     */
    private void getDbData() {
        ArrayList<String> saveList = new ArrayList<>();
        List<GoodRfidBean> list = dbManager.queryGoodList();
        for (GoodRfidBean bean : list) {
            saveList.add(bean.getRfid());
        }
        if (saveList.size() > 0) {
            LogPlus.e(saveList.toString());

            SumList.addAll(saveList);
            SumList = RfidHelper.removeDuplicateWithOrder(SumList);
            //  ToastUtil.show(SendGoodshActivity.this ,"存在未提交数据");
            SureDialog sureDialog = new SureDialog(SendGoodshActivity.this, "是否清空未提交的提交");
            sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                @Override
                public void sure() {
                    dbManager.deleteGoodAll();
                    SumList.clear();
                    mLaundryAdapter.setNewData(null);
                }

                @Override
                public void cancle() {

                }
            });

            queryOrderDetail1(saveList);
        }
        mOrderNumber.setText(String.valueOf(SumList.size()));
        mOrderTotal.setText(String.valueOf(SumList.size()));
    }

    /**
     * 保存数据到数据库
     */
    private void savaDb(ArrayList<String> list) {
        for (String string : list) {
            GoodRfidBean bean = new GoodRfidBean(null, string);
            dbManager.insertGood(bean);
        }
    }

    private void initRecyclerView() {
        mLaundryAdapter = new LaundryAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mLaundryAdapter);
        mOrderPopup = CommonPopupList.newBuilder(this)
            .setWidthEquals(mDropOrder)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    mTvOrder.setText(item);
                    OrderId = OrderList.get(position).id;
                }
            })
            .build();
        mHotelPopup = CommonPopupList.newBuilder(getActivity())
            .setWidthEquals(dropHotel)
            .setOnSelectItemListener(new CommonPopupList.OnSelectItemListener() {
                @Override
                public void onSelectItem(CommonPopupList popup, String item, int position) {
                    popup.dismiss();
                    // TODO: 2017/7/20
                    tvHotel.setText(item);
                    if (HotelList != null) {
                        HotelId = HotelList.get(position).getId();
                        OrderList.clear();
                        ordernoList.clear();
                        OrderId = null;
                        mTvOrder.setText("");
                        getWashListData(HotelId);
                    }
                }
            })
            .build();

        getPopupListData();
    }

    private void getPopupListData() {
        OrderProto.get().getHotel().
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<HotelBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(HotelBean hotelBean) {
                    if (hotelBean != null && hotelBean.getData() != null) {
                        List<String> datas = new ArrayList<>();

                        HotelBean.DataBean bean1 = new HotelBean.DataBean();
                        bean1.setTitle(getString(R.string.choose_all));
                        HotelList.add(bean1);
                        for (int i = 0; i < hotelBean.getData().size(); i++) {
                            HotelList.add(hotelBean.getData().get(i));
                        }
                        datas.add(getString(R.string.choose_all));
                        for (HotelBean.DataBean bean : hotelBean.getData()) {
                            datas.add(bean.getTitle());
                        }
                        mHotelPopup.setData(datas);
                    }
                }
            });
    }

    private void getWashListData(String id) {
        OrderProto.get().order_wash(id).
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<WashBackBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                    getBackListData(HotelId);
                }

                @Override
                public void onNext(WashBackBean hotelBean) {
                    OrderList = hotelBean.data.list;
                    if (OrderList != null) {
                        for (int i = 0; i < OrderList.size(); i++) {
                            ordernoList.add(OrderList.get(i).orderno);
                        }
                    }
                    getBackListData(HotelId);
                }
            });
    }

    private void getBackListData(String id) {
        OrderProto.get().order_back(id).
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<WashBackBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(WashBackBean hotelBean) {
                    //  OrderList = hotelBean.data.list;
                    OrderList.addAll(hotelBean.data.list);
                    if (hotelBean.data.list != null) {

                        for (int i = 0; i < hotelBean.data.list.size(); i++) {
                            ordernoList.add(hotelBean.data.list.get(i).orderno);
                        }
                    }
                    getRentListData(HotelId);
                }
            });
    }

    private void getRentListData(String id) {
        OrderProto.get().order_rent(id).
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<WashBackBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(WashBackBean hotelBean) {
                    //  OrderList = hotelBean.data.list;
                    OrderList.addAll(hotelBean.data.list);
                    if (hotelBean.data.list != null) {

                        for (int i = 0; i < hotelBean.data.list.size(); i++) {
                            ordernoList.add(hotelBean.data.list.get(i).orderno);
                        }
                        mOrderPopup.setData(ordernoList, true);
                    }
                }
            });
    }

    /**
     * 这是每一次的读取rfid的单独详情
     */
    private void queryOrderDetail1(final List<String> dflist) {
        if (dflist.size() == 0) {
            showOneToast("数据不能为空");
            return;
        }
        String rfid = "";
        for (int i = 0; i < dflist.size(); i++) {
            rfid = rfid + dflist.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            return;
        }
        mOrderNumber.setText(String.valueOf(rfids.size()));
        StockProto.get()
            .rfid_spec(rfid)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RFIDSpecListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                }

                @Override
                public void onNext(RFIDSpecListBean dataBean) {
                    mLaundryAdapter.setNewData(dataBean.data);
                }
            });
    }

    /**
     * 查询订单详情，这是是否保存之后，所有的rfid的详情
     */
    private void queryOrderDetail2(final List<String> dflist, final int type) {

        if (dflist != null) {
            SumList.addAll(dflist);
        }
        SumList = RfidHelper.removeDuplicateWithOrder(SumList);
        String rfid = "";
        mOrderTotal.setText(String.valueOf(SumList.size()));
        for (int i = 0; i < SumList.size(); i++) {
            rfid = rfid + SumList.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            return;
        }
        mOrderNumber.setText(String.valueOf(rfids.size()));
        StockProto.get()
            .rfid_spec(rfid)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RFIDSpecListBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                    if (type == 1) {
                        commit();
                    }
                }

                @Override
                public void onNext(RFIDSpecListBean dataBean) {
                    mLaundryAdapter.setNewData(dataBean.data);
                    if (type == 1) {
                        commit();
                    }
                }
            });
    }

    private void commitData() {
        String rfid = "";
        SumList = RfidHelper.removeDuplicateWithOrder(SumList);
        for (int i = 0; i < SumList.size(); i++) {
            rfid = rfid + SumList.get(i) + ",";
        }
        if (!TextUtils.isEmpty(rfid)) {
            rfid = rfid.substring(0, rfid.length() - 1);
        } else {
            return;
        }
        //  String hotel_id = UserHelper.get().gethotel_id();
        String order_wash_id = "", order_back_id = "", order_rent_id = "";
        String orderno = mTvOrder.getText().toString();
        if (TextUtils.isEmpty(OrderId)) {
            showOneToast("请先选择要送货的订单");
            return;
        }
        if (orderno.contains("W")) {
            order_wash_id = OrderId;
        } else if (orderno.contains("B")) {
            order_back_id = OrderId;
        } else if (orderno.contains("R")) {
            order_rent_id = OrderId;
        }
        StockProto.get()
            .order_deliver_new(rfid, order_wash_id, order_back_id, order_rent_id)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<BackBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    showOneToast(e.getMessage());
                }

                @Override
                public void onNext(BackBean dataBean) {
                    dbManager.deleteGoodAll();
                    showOneToast(dataBean.msg);
                    getDetailData(dataBean.data.order_id + "");
                }
            });
    }

    private void getDetailData(String id) {
        StockProto.get()
            .getOrderDetail("order_deliver_detail", id,
                new HttpProtocol.Callback<OrderDetailBean>() {
                    @Override
                    public void onSuccess(OrderDetailBean orderDetailBean) {
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), orderDetailBean.msg, Toast.LENGTH_SHORT)
                            .show();
                        Intent intent = new Intent(getActivity(), OrderDetailActivity1.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("detailData", orderDetailBean);
                        intent.putExtras(bundle);
                        intent.putExtra("type", 0);
                        startActivity(intent);
                    }

                    @Override
                    public void onFailed(int code, ErrorMsgException e) {
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        dismissLoadingDialog();
                    }
                });
    }

    @OnClick({ R.id.check, R.id.drop_order, R.id.btn_read_rfid, R.id.drop_hotel, R.id.btn_save })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check:
                if (rfids.size() > 0) {
                    SureDialog sureDialog =
                        new SureDialog(SendGoodshActivity.this, "上一次读取数据，还未保存，是否保存");
                    sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            savaDb(rfids);
                            queryOrderDetail2(rfids, 1);
                            rfids.clear();
                        }

                        @Override
                        public void cancle() {
                            commit();
                        }
                    });
                } else {
                    commit();
                }

                break;
            case R.id.drop_order:
                mOrderPopup.showAsDropDown(view);
                break;
            case R.id.drop_hotel:
                mHotelPopup.showAsDropDown(view);
                break;
            case R.id.btn_read_rfid:
                if (rfids.size() > 0) {
                    SureDialog sureDialog1 =
                        new SureDialog(SendGoodshActivity.this, "上一次读取数据，还未保存，是否保存");
                    sureDialog1.setOnCallBackListener(new SureDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            savaDb(rfids);
                            queryOrderDetail2(rfids, 0);
                            getData();
                            //kk++;
                            //test();
                        }

                        @Override
                        public void cancle() {
                            //kk++;
                            //test();
                            getData();
                        }
                    });
                } else {
                    //kk++;
                    //test();
                      getData();
                }

                break;
            case R.id.btn_save:
                ToastUtil.show(SendGoodshActivity.this, "保存成功");
                queryOrderDetail2(rfids, 0);
                savaDb(rfids);
                rfids.clear();

                break;
        }
    }

    private int kk = 0;

    private void test() {
        rfids.clear();
        if (kk == 1) {
            rfids.add("0002DEF59A5D");
        } else if (kk == 2) {
            rfids.add("0002DEF5D48D");
        } else if (kk == 3) {
            rfids.add("0002DEF6581E");
        }
        // rfids.add("0001D4CF76AE");
        //savaDb(rfids);
        queryOrderDetail1(rfids);
    }

    private void commit() {
        if (!(SumList.size() > 0)) {
            showOneToast("rfid不能为空");
            return;
        }
        SureDialog sureDialog = new SureDialog(SendGoodshActivity.this, "全部读取完成，确认提交");
        sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
            @Override
            public void sure() {
                commitData();
            }

            @Override
            public void cancle() {

            }
        });
    }

    private void getData() {
        rfids.clear();
        doReadDialog.showWorking(true);
        mBleWorker.check();
    }

    private void doReadRFID() {
        doReadDialog = DoResultDialog.newDialog(getActivity())
            .setSuccessImage(R.mipmap.ic_success)
            .setSuccessText(getString(R.string.scan_over))
            .setButton("完成扫描", new DoResultDialog.OnClickButtonListener() {
                @Override
                public void onClickButton(DoResultDialog dialog) {
                    mBleWorker.cancelCheck();
                }
            });

        doReadDialog.setCancelable(false);
    }

    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(getActivity())
            .setWorkingText(getString(R.string.commit_counting_result))
            .setSuccessImage(R.mipmap.ic_success)
            .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);
    }
}


